<?php

namespace App\Http\Controllers\Application;

use App\Http\Controllers\Controller;
use App\Http\Requests\Application\MuticolumnRequest;
use App\Models\Application\ColumnAsset;
use App\Models\Application\Columnrec;
use App\Models\Application\Muticolumn;
use App\Models\Application\Pagetpl;
use App\Models\Application\Paneltpl;
use App\Models\Application\TermType;
use App\Models\Recommend\ApppageRectpl;
use App\Models\Common\EntityData\Channel\Sp;
use App\Models\Entity\Asset\Video\Vasseti;
use App\Models\Entity\Column\Collist;
use App\Models\Entity\Column\ColumnType;
use App\Models\Entity\Tag\tag;
use App\Models\Recommend\MuticolumnReclist0Data;
use App\Repositories\Application\MuticolumnRepository;
use DB;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Storage;
use Response;

class MuticolumnController extends Controller
{
    use ModelForm;

    /** @var  MuticolumnRepository */
    private $muticolumnRepository;

    public function __construct(MuticolumnRepository $muticolumnRepo)
    {
        $this->muticolumnRepository = $muticolumnRepo;
    }

    /**
     * Display a listing of the Muticolumn.
     *
     * @return Response
     */
    public function index()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('application.muticolumns.index_header'));
            $content->description(__('application.muticolumns.index_description'));
            $content->body($this->grid());
            $content->row(view('application.muticolumns.column-assets.index'));
            $content->row(view('application.muticolumns.muticolumn-reclist0-datas.index'));
        });
    }

    /**
     * Show the form for creating a new Muticolumn.
     *
     * @return Response
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('application.muticolumns.create_header'));
            $content->description(__('application.muticolumns.create_description'));
            $content->body($this->form());

        });
    }

    /**
     * Store a newly created Muticolumn in storage.
     *
     * @param MuticolumnRequest $request
     *
     * @return Response
     */
    public function store(MuticolumnRequest $request)
    {
        $input = $request->all();
        // 设备类型默认为tv
        if (empty($input['term_type_id'])) {
            $input['term_type_id'] = 1;
        }

        $image = $request->file('img'); //使用laravel 自带的request类来获取一下文件.
        if ($image) {
            if ($image->isValid()) {
                // 允许上传的图片格式
                $allowed_extensions = ["png", "jpg", "gif", "jpeg"];
                if ($image->getClientOriginalExtension() && !in_array($image->getClientOriginalExtension(), $allowed_extensions)) {
                    return ['error' => 'You may only upload png, jpg, jpeg or gif.'];
                }
                $realPath = $image->getRealPath(); //临时文件的绝对路径
                // 获得图片的扩展名
                $extension = $image->getClientOriginalExtension();
                // 获取上传图片的文件名
                // $imagesName = $image->getClientOriginalName();
                // 重新命名上传文件名字
                $newImageName = md5(time()) . random_int(5, 5) . "." . $extension;
                // 上传图片
                $uploadConfig = config('custom.base.upload.muticolumn');
                $driver       = $uploadConfig['driver'];
                $dir          = $uploadConfig['dir'];
                $rootDir      = config('filesystems.disks.' . $driver . '.upload');
                // 图片的完整路径
                $fullPath = $rootDir . '/' . $dir . '/' . $newImageName;

                $input['img'] = $fullPath;

                $bool = Storage::disk($driver)->put($fullPath, file_get_contents($realPath));
            }
        }
        // 背景图片
        $backgroundImage = $request->file('bg'); //使用laravel 自带的request类来获取一下文件.
        if ($backgroundImage) {
            if ($backgroundImage->isValid()) {
                // 允许上传的图片格式
                $allowed_extensions = ["png", "jpg", "gif", "jpeg"];
                if ($backgroundImage->getClientOriginalExtension() && !in_array($backgroundImage->getClientOriginalExtension(), $allowed_extensions)) {
                    return ['error' => 'You may only upload png, jpg, jpeg or gif.'];
                }
                $bgRealPath = $backgroundImage->getRealPath(); //临时文件的绝对路径
                // 获得图片的扩展名
                $bgExtension = $backgroundImage->getClientOriginalExtension();
                // 获取上传图片的文件名
                // $imagesName = $image->getClientOriginalName();
                // 重新命名上传文件名字
                $newBackgroundImageName = md5(time()) . random_int(5, 5) . "." . $bgExtension;
                // 上传图片
                $uploadConfig = config('custom.base.upload.muticolumn');
                $driver       = $uploadConfig['driver'];
                $dir          = $uploadConfig['dir'];
                $rootDir      = config('filesystems.disks.' . $driver . '.upload');
                // 图片的完整路径
                $bgFullPath  = $rootDir . '/' . $dir . '/' . $newBackgroundImageName;
                $input['bg'] = $bgFullPath;

                $bool = Storage::disk($driver)->put($bgFullPath, file_get_contents($bgRealPath));
            }
        }
        $muticolumn = $this->muticolumnRepository->create($input);
        if ($muticolumn) {
            // 保存当前栏目列表的标签
            if (is_array($request->get('tags'))) {
                $muticolumn->tags()->attach(array_filter($request->get('tags')));
            }
        }

        Flash::success(__('application.muticolumns.saved_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('application.muticolumns.index'));

    }

    /**
     * Display the specified Muticolumn.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $muticolumn = $this->muticolumnRepository->findWithoutFail($id);

        if (empty($muticolumn)) {
            Flash::error(__('application.muticolumns.not_found'));

            return redirect(route('application.muticolumns.index'));
        }

        return view('application.muticolumns.show')->with('muticolumn', $muticolumn);

    }

    /**
     * Show the form for editing the specified Muticolumn.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {
        $muticolumn = $this->muticolumnRepository->findWithoutFail($id);

        if (empty($muticolumn)) {
            Flash::error(__('application.muticolumns.not_found'));

            return redirect(route('application.muticolumns.index'));
        }
        return Admin::content(function (Content $content) use ($id, $muticolumn) {

            $content->header(__('application.muticolumns.edit_header'));
            $content->description(__('application.muticolumns.edit_description'));

            $content->body($this->form()->edit($id));
            $range = $muticolumn->range ? $muticolumn->range : 0;
            $content->row(view('application.muticolumn.edit', ['range' => $range, 'tpl_id' => $muticolumn->tpl_id]));
        });
    }

    /**
     * Update the specified Muticolumn in storage.
     *
     * @param  int              $id
     * @param MuticolumnRequest $request
     *
     * @return Response
     */
    public function update($id, Request $request)
    {
        $muticolumn = $this->muticolumnRepository->findWithoutFail($id);

        if (empty($muticolumn)) {
            Flash::error(__('application.muticolumns.not_found'));

            return redirect(route('application.muticolumns.index'));
        }
        $input = $request->all();
        if (array_key_exists('_file_del_', $input)) {
            $bgtype       = $request->post('bg');
            $imgtype      = $request->post('img');
            $uploadConfig = config('custom.base.upload.muticolumn');
            $driver       = $uploadConfig['driver'];
            $dir          = $uploadConfig['dir'];
            if ($bgtype === '_file_del_') {
                $imgUrl = $muticolumn->bg;
                if ($flag = Storage::disk($driver)->delete($imgUrl)) {
                    $muticolumn->bg = null;
                    $muticolumn->save();
                    return response()->json(['message' => '图片删除成功!', 'status' => $flag]);
                }
            } elseif ($imgtype === '_file_del_') {
                $imgUrl = $muticolumn->img;
                if ($flag = Storage::disk($driver)->delete($imgUrl)) {
                    $muticolumn->img = null;
                    $muticolumn->save();
                    return response()->json(['message' => '图片删除成功!', 'status' => $flag]);
                }
                return response()->json(['message' => '图片删除失败!', 'status' => $flag]);
            }
        }
        $image = $request->file('img'); //使用laravel 自带的request类来获取一下文件.
        if ($image) {
            if ($image->isValid()) {
                // 允许上传的图片格式
                $allowed_extensions = ["png", "jpg", "gif", "jpeg"];
                if ($image->getClientOriginalExtension() && !in_array($image->getClientOriginalExtension(), $allowed_extensions)) {
                    return ['error' => 'You may only upload png, jpg, jpeg or gif.'];
                }
                $realPath = $image->getRealPath(); //临时文件的绝对路径
                // 获得图片的扩展名
                $extension = $image->getClientOriginalExtension();
                // 获取上传图片的文件名
                // $imagesName = $image->getClientOriginalName();
                // 重新命名上传文件名字
                $newImageName = md5(time()) . random_int(5, 5) . "." . $extension;
                // 上传图片
                $uploadConfig = config('custom.base.upload.muticolumn');
                $driver       = $uploadConfig['driver'];
                $dir          = $uploadConfig['dir'];
                $rootDir      = config('filesystems.disks.' . $driver . '.upload');

                // 图片的完整路径
                $fullPath = $rootDir . '/' . $dir . '/' . $newImageName;

                $input['img'] = $fullPath;
                $flag         = Storage::disk($driver)->delete($muticolumn->img);

                $bool = Storage::disk($driver)->put($fullPath, file_get_contents($realPath));
            }
        }
        // 背景图片
        $backgroundImage = $request->file('bg'); //使用laravel 自带的request类来获取一下文件.
        if ($backgroundImage) {
            if ($backgroundImage->isValid()) {
                // 允许上传的图片格式
                $allowed_extensions = ["png", "jpg", "gif", "jpeg"];
                if ($backgroundImage->getClientOriginalExtension() && !in_array($backgroundImage->getClientOriginalExtension(), $allowed_extensions)) {
                    return ['error' => 'You may only upload png, jpg, jpeg or gif.'];
                }
                $bgRealPath = $backgroundImage->getRealPath(); //临时文件的绝对路径
                // 获得图片的扩展名
                $bgExtension = $backgroundImage->getClientOriginalExtension();
                // 获取上传图片的文件名
                // $imagesName = $image->getClientOriginalName();
                // 重新命名上传文件名字
                $newBackgroundImageName = md5(time()) . random_int(5, 5) . "." . $bgExtension;
                // 上传图片
                $uploadConfig = config('custom.base.upload.muticolumn');
                $driver       = $uploadConfig['driver'];
                $dir          = $uploadConfig['dir'];
                $rootDir      = config('filesystems.disks.' . $driver . '.upload');
                // 图片的完整路径
                $bgFullPath  = $rootDir . '/' . $dir . '/' . $newBackgroundImageName;
                $input['bg'] = $bgFullPath;

                $flag = Storage::disk($driver)->delete($muticolumn->bg);

                $bool = Storage::disk($driver)->put($bgFullPath, file_get_contents($bgRealPath));
            }
        }

        $muticolumn = $this->muticolumnRepository->update($input, $id);
        if ($muticolumn) {
            // 保存当前栏目列表的标签
            if (is_array($request->get('tags'))) {
                // $muticolumn->tags()->detach();
                $muticolumn->tags()->sync(array_filter($request->get('tags')));
            }
        }
        Flash::success(__('application.muticolumns.updated_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('application.muticolumns.index'));
    }

    /**
     * Remove the specified Muticolumn from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        // 根据 `,` 判断传递过来的是单个id还是多个id
        if (substr_count($id, ',') >= 1) {
            $id = explode(",", $id);
        }

        // 如果是数组则进行批量删除
        if (is_array($id)) {
            if ($flag = $this->muticolumnRepository->batchDelete('id', $id)) {

                return response()->json(['message' => __('application.muticolumns.deleted_success'), 'status' => $flag]);
            } else {
                return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
            }
        }

        $muticolumn = $this->muticolumnRepository->findWithoutFail($id);

        if (empty($muticolumn)) {
            Flash::error(__('application.muticolumns.not_found'));

            return redirect(route('application.muticolumns.index'));
        }

        if ($flag = $this->muticolumnRepository->delete($id)) {
            $uploadConfig = config('custom.base.upload.muticolumn');
            $driver       = $uploadConfig['driver'];
            $deleteImg    = Storage::disk($driver)->delete($muticolumn->bg);
            $deleteImg    = Storage::disk($driver)->delete($muticolumn->img);
            // 取消与标签的关联
            $muticolumn->tags()->detach();
            return response()->json(['message' => __('application.muticolumns.deleted_success'), 'status' => $flag]);
        } else {
            return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
        }
    }

    /**
     * [form description]
     * @return {[type]} [description]
     */
    protected function form()
    {
        return Admin::form(Muticolumn::class, function (Form $form) {

            $form->display('id', 'ID');
            $form->text('name', '名称');
            $form->text('title', '标题');
            $form->text('subtitle', '副标题');
            $sps = Sp::pluck('name', 'id');
            $form->select('sp_id', 'Sp服务商')->options($sps);
            $tmpColumnTypes = ColumnType::get(['tags', 'id', 'title', 'pid'])->toArray();
            $tempArr        = [];
            foreach ($tmpColumnTypes as $key => $columnType) {
                $tags = explode(',', $columnType['tags']);
                foreach ($tags as $tag) {
                    if (in_array($tag, ['any', 'column'])) {
                        $tempArr[] = $columnType['id'];
                    }
                }
            }
            // $tmpColumnTypes = ColumnType::whereIn('id', $tempArr)->pluck('title', 'id');
            // $form->select('column_type_id', '栏目类型')->options($tmpColumnTypes);
            $columnTypes = ColumnType::whereIn('id', $tempArr)->get(['id', 'pid', 'title'])->toArray();
            $columnTypes = array_merge([['id' => 0, 'pid' => 0, 'title' => '选择']], $columnTypes);
            $form->ztree('column_type_id', '栏目类型')
                ->zTreeConfig(["map" => ["id" => "id", "title" => 'name', 'pid' => 'pId'], "type" => "radio", "open" => true])
                ->options($columnTypes);
            $collists = Collist::pluck('title', 'id');
            $form->select('collist_id', '栏目列表')->options($collists);
            // $form->textarea('data', '数据');
            $form->select('range', 'range')->options(array(
                '0' => '选择',
                '1' => 'area',
                '2' => 'page',
                '3' => 'app',
                '4' => 'list',
            ))->load('tpl_id', route('entity.column.collists.tpls'), 'id', 'title')->help('选中range时模板不能为空');;
            $paneltpls = Paneltpl::pluck('title', 'id')->toArray();
            $form->select('tpl_id', '模板')->options(array_merge(['0' => '选择'], $paneltpls));
            // 背景图
            $form->image('bg', '背景图')->removable();
            // message
            $form->text('message', 'message');

            // $paneltpls = Paneltpl::pluck('name', 'id');
            // $form->select('paneltpl_id', 'panel模板')->options($paneltpls);
            $form->image('img', '图片')->removable();
            $termTypes = TermType::pluck('name', 'id');
            $form->select('term_type_id', '设备类型')->options($termTypes)->default(1);
            $form->radio('active', 'active')->options(['1' => '可用', '0' => '不可用'])->default(1);
            $tags = tag::pluck('name', 'id');
            $form->multipleSelect('tags', '标签')->options($tags);
            $form->text('short_desc', '简介');
            $form->textarea('description', '详述');
            $form->number('listorder', '排序');

            // $form->display('created_at', __('base.created_at'));
            // $form->display('updated_at', __('base.updated_at'));

        });
    }

    /**
     * [grid description]
     * @return {[type]} [description]
     */
    protected function grid()
    {

        return Admin::grid(Muticolumn::class, function (Grid $grid) {
            // 考虑是否需要scope和排序
            // $grid->model()->orderBy('listorder', 'asc');

            // // 添加按钮
            // if (!\Gate::check('application.muticolumns.create')) {
            //     $grid->disableCreation();
            // }

            // // 编辑和删除按钮
            // $grid->actions(function ($actions) {
            //     // 编辑按钮
            //     if (!\Gate::check('application.muticolumns.edit')) {
            //         $actions->disableEdit();
            //     }
            //     // 删除按钮
            //     if (!\Gate::check('application.muticolumns.destroy')) {
            //         $actions->disableDelete();
            //     }
            // });

            // // 导出按钮
            // if (!\Gate::check('application.muticolumns.export')) {
            //     $grid->disableExport();
            // }

            // // 批量操作
            // $grid->tools(function ($tools) {
            //     $tools->batch(function ($batch) {
            //         // 批量删除按钮
            //         if (!\Gate::check('application.muticolumns.batch_destroy')) {
            //             $batch->disableDelete();
            //         }
            //     });
            // });

            // 添加按钮
            if (Admin::user()->cannot('application.muticolumns.create')) {
                $grid->disableCreation();
            }

            // 导出按钮
            if (Admin::user()->cannot('application.muticolumns.export')) {
                $grid->disableExport();
            }

            // 批量操作
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    // 批量删除按钮
                    if (Admin::user()->cannot('application.muticolumns.batch_destroy')) {
                        $batch->disableDelete();
                    }
                });
            });

            // 编辑和删除按钮
            $grid->actions(function ($actions) {
                $id         = $actions->getKey();
                $paneltplId = $actions->row->paneltpl_id;
                // 编辑按钮
                if (Admin::user()->cannot('application.muticolumns.edit')) {
                    $actions->disableEdit();
                }
                // 删除按钮
                if (Admin::user()->cannot('application.muticolumns.destroy')) {
                    $actions->disableDelete();
                }

                // append一个操作
                $url = route('application.muticolumns.column.content', ['muticolumn_id' => $id]);
                $actions->prepend('<a href="' . $url . '">编辑栏目数据/&nbsp;&nbsp;</a>');
                //添加推荐数据
                $url = route('application.muticolumns.add_asset_data', ['muticolumn_id' => $id, '_t' => rand(100000000, 900000000)]);
                $actions->append('<a href="' . $url . '" data-toggle="modal"  data-target="#add-content-tag-modal" title="添加栏目数据">&nbsp;&nbsp;添加栏目数据/&nbsp;&nbsp;</a>');

                // $url = route('application.muticolumns.column.add_asset_data', ['muticolumn_id' => $id, '_t' => rand(100000000, 900000000)]);
                // $actions->append('<a href="' . $url . '" data-toggle="modal"  data-target="#add-content-tag-modal" title="推荐数据编辑">&nbsp;&nbsp;推荐数据编辑/&nbsp;&nbsp;</a>');
                // 跳转到模板区位信息定义
                // $actions->append('<a href=' . route('application.columnrecs.index', ['muticolumn_id' => $id, 'paneltpl_id' => $paneltplId]) . ' onclick="" title="推荐位模板数据编辑">推荐位模板数据编辑/&nbsp;&nbsp;</a>');
            });
            $grid->column('id', 'ID')->sortable();
            $grid->column('name', '名称')->sortable();
            $grid->column('title', '标题')->sortable();
            $grid->column('subtitle', '副标题')->sortable();
            $grid->column('sp.title', 'Sp服务商')->sortable();
            $grid->column('collist.title', '栏目列表')->sortable();
            $grid->column('columnType.title', '栏目类型')->sortable();
            $grid->column('range', 'range')->display(function ($val) {
                switch ($val) {
                    case '1':
                        return '<span class="badge bg-green">area</span>';
                        break;
                    case '2':
                        return '<span class="badge bg-green">page</span>';
                        break;
                    case '3':
                        return '<span class="badge bg-green">app</span>';
                        break;
                    case '4':
                        return '<span class="badge bg-green">list</span>';
                        break;
                    default:
                        return '';
                        break;
                }
            });
            $grid->column('tpl_id', '模板')->display(function ($val) {
                $returnName = '';
                switch ($this->range) {
                    case '1':
                        $returnName = Paneltpl::where(['id' => $val])->value('title');
                        break;
                    default:
                        $returnName = Pagetpl::where(['id' => $val])->value('title');
                        break;
                }
                return empty($returnName) ? '' : $returnName;
            });

            $uploadConfig = config('custom.base.upload.muticolumn');
            $driver       = $uploadConfig['driver'];
            $dir          = $uploadConfig['dir'];
            $uploadHosts  = config('custom.base.host');
            $host         = $uploadHosts[$driver];
            // 背景图
            $grid->column('bg', '背景图')->image($host);
            // 信息
            $grid->column('message', 'message')->sortable();
            // $grid->column('paneltpl.title', 'panel模板')->sortable();
            $grid->column('termType.title', '设备类型')->sortable();
            $grid->tags('标签')->pluck('name')->label();
            $grid->column('active', 'active')->display(function ($val) {
                $returnName = '';
                if (!empty($val)) {
                    return '<span class="badge bg-green">可用</span>';
                }
                return '<span class="badge bg-orange">不可用</span>';
            });
            // $grid->column('data', '栏目推荐数据')->display(function ($val) {
            //     $url   = route('recommend.muticolumn_reclist0_datas.index', ['muticolumn_id' => $this->id]);
            //     $count = MuticolumnReclist0Data::where(['muticolumn_id' => $this->id])->count();
            //     $data  = "<a target='_blank' href=" . $url . ">" . $count . "条数据</a>";
            //     return $data;
            // });
            $grid->column('img', '图片')->image($host);
            $grid->column('listorder', '排序')->sortable();

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // 设备类型
                $tmpTermTypes = TermType::pluck('title', 'id');
                $filter->equal('term_type_id', '设备类型')->select($tmpTermTypes);
                // 页面
                $tmpColumnTypes = ColumnType::pluck('title', 'id');
                $filter->equal('column_type_id', '栏目类型')->select($tmpColumnTypes);
                // // 禁用id查询框
                // $filter->disableIdFilter();
                $filter->like('name', '名称');

            });
        });
    }

    /**
     * 查看栏目数据编辑
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function dataView(Request $request)
    {
        $id         = $request->input('id');
        $paneltplId = $request->input('paneltpl_id');

        $muticolumn = $this->muticolumnRepository->findWithoutFail($id);

        if (empty($muticolumn)) {
            Flash::error(__('application.muticolumns.not_found'));

            return redirect(route('application.muticolumns.index'));
        }
        // 获取栏目推荐区位信息定义
        $columnrecs = Columnrec::where(['id' => $id, 'paneltpl_id' => $paneltplId])->get();
        if (empty($columnrecs->first())) {
            // 获取panel模板信息
            $paneltpl = Paneltpl::where(['id' => $paneltplId])->first();
            // dd(123);
            $areas = explode('/', $paneltpl->areas);
            // dd($areas);
            $columnrecDatas = [];
            if (!empty($areas)) {
                foreach ($areas as $key => $area) {
                    $columnrecDatas[$key]['muticolumn_id'] = intval($id);
                    $columnrecDatas[$key]['paneltpl_id']   = intval($paneltplId);
                    $columnrecDatas[$key]['area']          = $area;
                }
            }
            // $result = Columnrec::create($columnrecDatas);
            $result = DB::table('columnrecs')->insert($columnrecDatas);
            if (empty($result)) {
                Flash::error(__('application.muticolumns.not_found'));

                return redirect(route('application.muticolumns.index'));
            }
        }

    }

    /**
     * 添加媒资数据
     * @param Request $request [description]
     */
    public function addAssetData(Request $request)
    {
        $muticolumnId = $request->input('muticolumn_id');

        $columnrec = $this->muticolumnRepository->findWithoutFail($muticolumnId);

        if (empty($columnrec)) {
            Flash::error(__('application.muticolumns.not_found'));

            return redirect(route('application.muticolumns.index'));
        }
        $datas = [];
        $data  = [
            [
                'id'    => '1',
                'title' => '视频',
            ],
            [
                'id'    => '2',
                'title' => '音频',
            ],
            [
                'id'    => 3,
                'title' => '图文',
            ],
        ];
        $datas['datas']         = $data;
        $datas['muticolumn_id'] = $muticolumnId;
        return view('application.muticolumns.column-assets.create', $datas);
    }

    /**
     * 根据节目类型获取数据源
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function getDataByAssetType(Request $request)
    {
        // 搜索框的值
        $search_value = $request->input('search_value');
        // 媒资类型
        $assetType = $request->input('asset_type');
        // 栏目ID
        $muticolumnId = $request->input('muticolumn_id');
        $relation     = [];
        $whereData    = [];
        // 获取媒资ID
        $selectAssetId = ColumnAsset::where([
            'muticolumn_id' => $muticolumnId,
            'asset_type'    => $assetType,
        ])
            ->pluck('asset_id')
            ->toArray();
        switch ($assetType) {
            case '1':
                $model    = new Vasseti();
                $relation = ['vcat', 'actors', 'directors', 'vareas', 'vlangs', 'vyears', 'vcattags'];

                break;case 'aasset':
                $model    = new Vasseti();
                $relation = ['vcat', 'actors', 'directors', 'vareas', 'vlangs', 'vyears', 'vcattags'];
                break;
            case '2':
                $model    = new Vasseti();
                $relation = ['vcat', 'actors', 'directors', 'vareas', 'vlangs', 'vyears', 'vcattags'];
                break;
            case '3':
                $model    = new Vasseti();
                $relation = ['vcat', 'actors', 'directors', 'vareas', 'vlangs', 'vyears', 'vcattags'];
                break;
            default:
                $model    = new Vasseti();
                $relation = ['vcat', 'actors', 'directors', 'vareas', 'vlangs', 'vyears', 'vcattags'];
                break;
        }

        $model = (new \ReflectionClass($model))->getName();

        $data         = [];
        $data['draw'] = $request->get('draw');
        $start        = $request->get('start') ?: 0;
        $length       = $request->get('length') ?: 10;
        $order        = $request->get('order');
        $columns      = $request->get('columns');
        $search       = $request->get('search');
        if ($order) {
            $orderColumData = $columns[$order[0]['column']]['data'];
        }

        // 排序字段
        $ord = '';
        if (!empty($orderColumData)) {
            $ord = $orderColumData . ' ' . $order[0]['dir'];
        } else {
            $ord = 'id asc';
        }
        $data['recordsTotal']    = $model::whereNotIn('id', $selectAssetId)->where($whereData)->count();
        $data['recordsFiltered'] = $model::whereNotIn('id', $selectAssetId)->where($whereData)->count();
        $data['data']            = $model::with($relation)
            ->whereNotIn('id', $selectAssetId)
            ->where($whereData)
            ->skip($start)->take($length)
            ->orderByRaw($ord)
            ->get();
        return response()->json($data);
    }

    /**
     * 保存节目推荐数据
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function assetDataStore(Request $request)
    {
        // 获取传递过来是哪个栏目
        $muticolumnId = $request->input('muticolumn_id');
        if (empty($muticolumnId)) {
            return response()->json(['content' => '栏目不能为空', 'status' => false]);
        }
        // 获取数据类型
        $assetType = $request->input('asset_type');
        if (empty($assetType)) {
            return response()->json(['content' => '媒资类型不能为空', 'status' => false]);
        }
        // 获取所有传递来的数据ID
        $dataId = $request->input('data_id');
        if (!is_array($dataId)) {
            return response()->json(['content' => '数据为空,请选择数据', 'status' => false]);
        }
        $datas = [];
        DB::beginTransaction();
        try {
            foreach ($dataId as $key => $value) {
                $columnAsset = DB::table('column_assets')
                    ->whereNull('deleted_at')
                    ->where(['muticolumn_id' => $muticolumnId, 'asset_type' => $assetType, 'asset_id' => $value])
                    ->first();
                if (empty($columnAsset)) {
                    $datas[$key]['muticolumn_id'] = $muticolumnId;
                    $datas[$key]['asset_type']    = $assetType;
                    $datas[$key]['asset_id']      = $value;
                }
            }
            DB::table('column_assets')->insert($datas);
            DB::commit();
            return response()->json(['content' => '添加成功！', 'status' => true]);
        } catch (Exception $e) {
            DB::rollback();
            return response()->json(['content' => '添加失败！', 'status' => false]);
        }
    }

    /**
     * 添加栏目媒资推荐数据
     * @param Request $request [description]
     */
    public function addColumnAssetData(Request $request)
    {
        $muticolumnId = $request->input('muticolumn_id');

        $columnrec = $this->muticolumnRepository->findWithoutFail($muticolumnId);

        if (empty($columnrec)) {
            Flash::error(__('application.muticolumns.not_found'));

            return redirect(route('application.muticolumns.index'));
        }
        $datas = [];
        $data  = [
            [
                'id'    => '1',
                'title' => '视频',
            ],
            [
                'id'    => '2',
                'title' => '音频',
            ],
            [
                'id'    => 3,
                'title' => '图文',
            ],
        ];
        $datas['datas']         = $data;
        $datas['muticolumn_id'] = $muticolumnId;
        return view('application.muticolumns.muticolumn-reclist0-datas.create', $datas);
    }

    /**
     * 根据栏目节目类型获取数据源
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function getColumnDataByAssetType(Request $request)
    {
        // 搜索框的值
        $search_value = $request->input('search_value');
        // 媒资类型id
        $columnAssetType = $request->input('column_asset_type');
        // 栏目ID
        $muticolumnId = $request->input('muticolumn_id');
        $relation     = [];
        $whereData    = [];
        switch ($columnAssetType) {
            case '1':
                $model    = new Vasseti();
                $relation = ['vcat', 'actors', 'directors', 'vareas', 'vlangs', 'vyears', 'vcattags'];
                break;case 'aasset':
                $model    = new Vasseti();
                $relation = ['vcat', 'actors', 'directors', 'vareas', 'vlangs', 'vyears', 'vcattags'];
                break;
            case '2':
                $model    = new Vasseti();
                $relation = ['vcat', 'actors', 'directors', 'vareas', 'vlangs', 'vyears', 'vcattags'];
                break;
            case '3':
                $model    = new Vasseti();
                $relation = ['vcat', 'actors', 'directors', 'vareas', 'vlangs', 'vyears', 'vcattags'];
                break;
            default:
                $model    = new Vasseti();
                $relation = ['vcat', 'actors', 'directors', 'vareas', 'vlangs', 'vyears', 'vcattags'];
                break;
        }
        $model = (new \ReflectionClass($model))->getName();

        $assetIds = ColumnAsset::where([
            'asset_type'    => $columnAssetType,
            'muticolumn_id' => $muticolumnId,
        ])
            ->pluck('asset_id')
            ->toArray();
        $data         = [];
        $data['draw'] = $request->get('draw');
        $start        = $request->get('start') ?: 0;
        $length       = $request->get('length') ?: 10;
        $order        = $request->get('order');
        $columns      = $request->get('columns');
        $search       = $request->get('search');
        if ($order) {
            $orderColumData = $columns[$order[0]['column']]['data'];
        }

        // 排序字段
        $ord = '';
        if (!empty($orderColumData)) {
            $ord = $orderColumData . ' ' . $order[0]['dir'];
        } else {
            $ord = 'id asc';
        }
        $data['recordsTotal']    = $model::where($whereData)->whereIn('id', $assetIds)->count();
        $data['recordsFiltered'] = $model::where($whereData)->whereIn('id', $assetIds)->count();
        $data['data']            = $model::with($relation)
            ->whereIn('id', $assetIds)
            ->where($whereData)
            ->skip($start)->take($length)
            ->orderByRaw($ord)
            ->get();
        // dd($data);
        return response()->json($data);
    }

    /**
     * 保存节目推荐数据
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function columnAssetDataStore(Request $request)
    {
        // 获取传递过来是哪个栏目
        $muticolumnId = $request->input('muticolumn_id');
        if (empty($muticolumnId)) {
            return response()->json(['content' => '栏目不能为空', 'status' => false]);
        }
        // 获取数据类型
        $columnAssetType = $request->input('column_asset_type');
        if (empty($columnAssetType)) {
            return response()->json(['content' => '媒资类型不能为空', 'status' => false]);
        }
        // 获取所有传递来的数据ID
        $dataId = $request->input('data_id');
        if (!is_array($dataId)) {
            return response()->json(['content' => '数据为空,请选择数据', 'status' => false]);
        }
        $datas = [];
        DB::beginTransaction();
        try {
            foreach ($dataId as $key => $value) {
                $muticolumnReclistDatas = DB::table('muticolumn_reclist0_datas')
                    ->whereNull('deleted_at')
                    ->where(['muticolumn_id' => $muticolumnId, 'data_id' => $columnAssetType, 'resource_data_id' => $value])
                    ->first();
                // 判断此栏目数据是否已存在
                if (empty($muticolumnReclistDatas)) {
                    // 根据类型获取资源名称
                    switch ($columnAssetType) {
                        case '1':
                            $result = Vasseti::where(['id' => $value])->first();
                            break;
                        case '2':
                            $result = Vasseti::where(['id' => $value])->first();
                            break;
                        case '3':
                            $result = Vasseti::where(['id' => $value])->first();
                            break;
                        default:
                            # code...
                            break;
                    }
                    if (!empty($result)) {
                        $datas[$key]['name']             = $result->name;
                        $datas[$key]['title']            = $result->title;
                        $datas[$key]['subtitle']         = $result->subtitle;
                        $datas[$key]['muticolumn_id']    = $muticolumnId;
                        $datas[$key]['data_id']          = $columnAssetType;
                        $datas[$key]['resource_data_id'] = $value;
                        $datas[$key]['meta_id']          = 0;
                        $datas[$key]['created_at']       = date('Y-m-d H:i:s');
                    }
                }
            }
            DB::table('muticolumn_reclist0_datas')->insert($datas);
            DB::commit();
            return response()->json(['content' => '添加成功！', 'status' => true]);
        } catch (Exception $e) {
            DB::rollback();
            return response()->json(['content' => '添加失败！', 'status' => false]);
        }
    }

    /**
     * 查看栏目节目数据
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function assetContentView($muticolumnId, Request $request)
    {
        $muticolumn = $this->muticolumnRepository->findWithoutFail($muticolumnId);
        if (empty($muticolumn)) {
            Flash::error(__('application.muticolumns.not_found'));

            return redirect(route('application.muticolumns.index'));
        }
        $edit_header      = '栏目节目数据';
        $edit_description = '详情';
        $dataTypes        = [
            [
                'id'    => '1',
                'title' => '视频',
            ],
            [
                'id'    => '2',
                'title' => '音频',
            ],
            [
                'id'    => 3,
                'title' => '图文',
            ],
        ];
        return view('application.muticolumns.muticolumn-assets.index',
            compact('edit_header', 'edit_description', 'muticolumn', 'dataTypes'));
    }

    /**
     * 获取栏目当前已选数据
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function getSelectedAssets(Request $request)
    {
        // 搜索框的值
        $search_value = $request->input('search_value');
        // 栏目ID
        $muticolumnId = $request->input('muticolumn_id');
        // 数据类型
        $dataType = $request->input('data_type');
        // dd($dataType);
        $data                 = array();
        $data['draw']         = $request->get('draw');
        $start                = $request->get('start') ?: 0;
        $length               = $request->get('length') ?: 10;
        $order                = $request->get('order');
        $columns              = $request->get('columns');
        $search               = $request->get('search');
        $data['recordsTotal'] = DB::table('column_assets')->where(['muticolumn_id' => $muticolumnId])->count();

        if ($order) {
            $orderColumData = $columns[$order[0]['column']]['data'];
        }
        // 排序字段
        $ord = '';
        if (!empty($orderColumData)) {
            $ord = $orderColumData . ' ' . $order[0]['dir'];
        } else {
            $ord = 'id asc';
        }
        $data['recordsFiltered'] = DB::table('column_assets')->where(['muticolumn_id' => $muticolumnId])->count();

        try {
            if (empty($dataType)) {
                //  媒资
                $vassets = DB::table('column_assets as c')
                    ->select(['c.id', 'c.asset_type', 'v.name', 'v.title', 'v.subtitle'])
                    ->where(['c.asset_type' => 1, 'c.muticolumn_id' => $muticolumnId])
                    ->whereNull('c.deleted_at')
                    ->leftJoin('vassetis as v', 'c.asset_id', '=', 'v.id')
                    ->get();
                // 音频
                $aassets = DB::table('column_assets as c')
                    ->select(['c.id', 'c.asset_type', 'v.name', 'v.title', 'v.subtitle'])
                    ->where(['c.asset_type' => 2, 'c.muticolumn_id' => $muticolumnId])
                    ->whereNull('c.deleted_at')
                    ->leftJoin('vassetis as v', 'c.asset_id', '=', 'v.id')
                    ->get();
                // 媒资音频合并
                $merged = $vassets->merge($aassets);

                // 图文
                $tassets = DB::table('column_assets as c')
                    ->select(['c.id', 'c.asset_type', 'v.name', 'v.title', 'v.subtitle'])
                    ->where(['c.asset_type' => 3, 'c.muticolumn_id' => $muticolumnId])
                    ->whereNull('c.deleted_at')
                    ->leftJoin('vassetis as v', 'c.asset_id', '=', 'v.id')
                    ->get();
                $selectedMerged = $merged->merge($tassets);
            }
            if ($dataType == 1) {
                $selectedMerged = DB::table('column_assets as c')
                    ->select(['c.id', 'c.asset_type', 'v.name', 'v.title', 'v.subtitle'])
                    ->where(['c.asset_type' => 1, 'c.muticolumn_id' => $muticolumnId])
                    ->whereNull('c.deleted_at')
                    ->leftJoin('vassetis as v', 'c.asset_id', '=', 'v.id')
                    ->get();
            } elseif ($dataType == 2) {
                $selectedMerged = DB::table('column_assets as c')
                    ->select(['c.id', 'c.asset_type', 'v.name', 'v.title', 'v.subtitle'])
                    ->where(['c.asset_type' => 2, 'c.muticolumn_id' => $muticolumnId])
                    ->whereNull('c.deleted_at')
                    ->leftJoin('vassetis as v', 'c.asset_id', '=', 'v.id')
                    ->get();
            } elseif ($dataType == 3) {
                $selectedMerged = DB::table('column_assets as c')
                    ->select(['c.id', 'c.asset_type', 'v.name', 'v.title', 'v.subtitle'])
                    ->where(['c.asset_type' => 3, 'c.muticolumn_id' => $muticolumnId])
                    ->whereNull('c.deleted_at')
                    ->leftJoin('vassetis as v', 'c.asset_id', '=', 'v.id')
                    ->get();
            }

        } catch (Exception $e) {
            dd($e->getMessage());
        }
        $data['data'] = $selectedMerged;
        return response()->json($data);
    }

    /**
     * 删除单个资源|多个资源
     * @param  [type] $album_id   [description]
     * @param  [type] $vasseti_id [description]
     * @return [type]             [description]
     */
    public function deleteAsset(Request $request)
    {
        $muticolumn_id = $request->input('muticolumn_id');
        $asset_id      = $request->input('asset_id');

        if (empty($muticolumn_id)) {
            return response()->json(['content' => '专题为空!', 'status' => false]);
        }
        if (empty($asset_id)) {
            return response()->json(['content' => '媒资为空!', 'status' => false]);
        }
        // 判断是否为批量删除
        if (is_array($asset_id)) {
            foreach ($asset_id as $value) {
                $flag = ColumnAsset::where(['id' => $value])->delete();

                if (!$flag) {
                    return response()->json(['content' => '删除失败!', 'status' => $flag]);
                }
            }
            return response()->json(['content' => '删除成功!', 'status' => true]);
        }

        $flag = ColumnAsset::where(['id' => $asset_id])->delete();

        if ($flag) {
            return response()->json(['content' => '删除成功!', 'status' => $flag]);
        } else {
            return response()->json(['content' => '删除失败!', 'status' => $flag]);

        }
    }
}
